package utils

import (
    "sync"
    "time"
)

const (
    Online = iota
    Offline
)

type Alive struct {
    ts_begin time.Time
    ts_last  time.Time
    status   int
    mu       sync.Mutex
    maxIdle  time.Duration
}

func NewAlive(max_idle time.Duration) *Alive {
    x := &Alive{}
    x.status = Offline
    x.maxIdle = max_idle
    return x
}

func (s *Alive) Update() {
    s.mu.Lock()
    defer s.mu.Unlock()

    s.ts_last = time.Now()

    if s.status == Offline {
        s.ts_begin = s.ts_last
        s.status = Online
        return
    }
}

func (s *Alive) AliveInfo() (alive bool, tBegin time.Time, tLast time.Time) {
    s.mu.Lock()
    defer s.mu.Unlock()
    tBegin = s.ts_begin
    tLast = s.ts_last


    if s.status == Offline {
        alive = false
        return
    }


    if time.Now().Sub(s.ts_last) > s.maxIdle {
        s.status = Offline
        alive = false
        return
    }
    return true, s.ts_begin, s.ts_last
}
